package cn.xej.boot_redis01.controller;

import cn.xej.boot_redis01.aop.FieldSumbit;
import cn.xej.boot_redis01.mapper.TbUserMapper;
import cn.xej.boot_redis01.pojo.TbUser;
import cn.xej.boot_redis01.pojo.UserVo;
import cn.xej.boot_redis01.service.TbUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author <a href="mailto:enjie.xu@yunhutech.com">xiaoming</a>
 * @since 2021/6/28
 */
@RestController
public class GoodController {

    private static final String REDIS_LOCK = "lock";

//    @Autowired
//    private StringRedisTemplate redisTemplate;

//    @Autowired
//    private Redisson redisson;

    @Value("${server.port}")
    private String serverPort;


    @Autowired
    private TbUserService tbUserService;

    @Autowired
    private TbUserMapper userMapper;

    @PostMapping("/hello")
    @FieldSumbit
    public List<TbUser> getUsers(@RequestBody  TbUser tbUser){
        List<TbUser> users = tbUserService.users();
        return users;
    }


    @GetMapping("/index")
    public List<UserVo> getUserVos(){
        return userMapper.getUserVos();
    }

//    @GetMapping("/buy_goods")
//    public String buy_goods() throws Exception {
//        //当前请求的UUID + 线程名
//        String value = UUID.randomUUID().toString() + Thread.currentThread().getName();
//        //获取锁
//        RLock redissonLock = redisson.getLock(REDIS_LOCK);
//        //上锁
//        redissonLock.lock();
//        try {
//
//            //从redis中获取商品剩余的数量
//            String o = redisTemplate.opsForValue().get("goods");
//            int num = o == null ? 0 : Integer.parseInt(o);
//            String str = null;
//
//            if (num > 0) {
//                int realNum = num - 1;
//                redisTemplate.opsForValue().set("goods", realNum + "");
//                str = "你已经成功秒杀商品，此时还剩余：" + realNum + "件" + "\t 服务器端口: " + serverPort;
//
//            } else {
//                str = "商品已经售罄/活动结束/调用超时，欢迎下次光临" + "\t 服务器端口: " + serverPort;
//            }
//            System.out.println(str);
//            return str;
//        } finally {
//            // 还在持有锁的状态，并且是当前线程持有的锁再解锁
//            if (redissonLock.isLocked() && redissonLock.isHeldByCurrentThread()){
//                redissonLock.unlock();
//            }
//
////            //判断是否是自己加的锁
////            if (value.equalsIgnoreCase(redisTemplate.opsForValue().get(REDIS_LOCK))){
////                redisTemplate.delete(REDIS_LOCK);
////            }
//        }
//    }

}
